package org.jeecg.modules.goldentry.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.goldentry.entity.GoldEntry;
import org.jeecg.modules.goldentry.mapper.GoldEntryMapper;
import org.jeecg.modules.goldentry.service.IGoldEntryService;
import org.jeecg.modules.manage.entity.CustomerInfo;
import org.jeecg.modules.manage.service.ICustomerInfoService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description:  金出入库
 * @Author: jerryzhu
 * @Date:   2021-11-15
 * @Version: V1.0
 */
@Api(tags=" 金出入库")
@RestController
@RequestMapping("/goldEntry")
@Slf4j
public class GoldEntryController extends JeecgController<GoldEntry, IGoldEntryService> {
	
	@Autowired
	private IGoldEntryService goldEntryService;
	
	@Autowired
	private GoldEntryMapper goldEntryMapper;
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private ICustomerInfoService customerInfoService;
	
	
	
	/**
	 * 金出入库明细分页列表
	 *
	 * @param goldEntry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = " 金出入库-金出入库明细分页")
	@ApiOperation(value=" 金出入库-金出入库明细分页列表", notes=" 金出入库-金出入库明细分页列表")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(GoldEntry goldEntry,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GoldEntry> queryWrapper = QueryGenerator.initQueryWrapper(goldEntry, req.getParameterMap());
		Page<GoldEntry> page = new Page<GoldEntry>(pageNo, pageSize);
		IPage<GoldEntry> pageList = goldEntryService.selectGoldEntryPage(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 仓库库存数据列表
	 *
	 * @param goldEntry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = " 金出入库-仓库库存数据列表")
	@ApiOperation(value=" 金出入库-仓库库存数据列表", notes=" 金出入库-仓库库存数据列表")
	@GetMapping(value = "/queryStorageData")
	public Result<?> queryStorageData(@RequestParam(name="storageId",required = true) String storageId)  {
		List<GoldEntry> list = goldEntryService.getGoldEntryStorageSummaryList(storageId);
		return Result.OK(list);
	}
	
	/**
	 * 员工库存数据列表
	 *
	 * @param goldEntry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = " 金出入库-员工库存数据列表")
	@ApiOperation(value=" 金出入库-员工库存数据列表", notes=" 金出入库-员工库存数据列表")
	@GetMapping(value = "/queryPersonData")
	public Result<?> queryPersonData(@RequestParam(name="userId",required = true) String userId)  {
		List<GoldEntry> list = goldEntryService.getGoldEntryPersonSummaryList(userId);
		return Result.OK(list);
	}
	
	
	/**
	 *   批量添加
	 *
	 * @param goldEntry
	 * @return
	 */
	@AutoLog(value = " 金出入库-批量添加")
	@ApiOperation(value=" 金出入库-批量添加", notes=" 金出入库-批量添加")
	@PostMapping(value = "/batchAdd")
	@Transactional
	public Result<?> batchAdd(@RequestBody JSONObject jsonObject) {
		String sendPerson = jsonObject.getString("sendPerson");//发出员工
		String sendStorage = jsonObject.getString("sendStorage");//发出仓库
		String sendCustomer = jsonObject.getString("sendCustomer");//发出客户
		String receivePerson = jsonObject.getString("receivePerson");//接收员工
		String receiveStorage = jsonObject.getString("receiveStorage");//接收仓库
		String receiveCustomer = jsonObject.getString("receiveCustomer");//接收客户
		Integer type = jsonObject.getInteger("type");//出入库类型
		String jsonString = JSONArray.toJSONString(jsonObject.get("data"));
		JSONArray jsonArray = JSONArray.parseArray(jsonString);
		Date now = new Date();//当前时间
		if(jsonArray != null && jsonArray.size() > 0) {
			for(int i = 0; i<jsonArray.size(); i++) {
				String str = JSONArray.toJSONString(jsonArray.get(i));
				JSONObject obj = JSONObject.parseObject(str);
				String id = obj.getString("id");//working_order_record表的主键ID
				if(id != null && !"".equals(id)) {
					String karat = obj.getString("karat");
					BigDecimal withStoneWeight = obj.getBigDecimal("withStoneWeight");//连石重
					if(karat == null || "".equals(karat) || withStoneWeight == null) {
						continue;//成色和连石重都是必填项，所以如果成色或者连石重为空，则跳过此行数据
					}
					GoldEntry goldEntry = new GoldEntry();
					goldEntry.setGoldActionType(type);//操作类型
					goldEntry.setSn("GON-"+System.currentTimeMillis());//操作流水号
					goldEntry.setSendPerson(sendPerson);//发出员工
					goldEntry.setSendStorage(sendStorage);//发出仓库
					goldEntry.setSendCustomer(sendCustomer);//发出客户
					goldEntry.setSendTime(now);//发出时间
					goldEntry.setReceivePerson(receivePerson);//接收员工
					goldEntry.setReceiveStorage(receiveStorage);//接收仓库
					goldEntry.setReceiveCustomer(receiveCustomer);//接收客户
					goldEntry.setReceiveTime(now);//接收时间
					goldEntry.setName(obj.getString("name"));//来料名称
					goldEntry.setWorkNum(obj.getString("workNum"));//工单号
					goldEntry.setPn(obj.getString("pn"));//拆分页
					goldEntry.setOrderCodeNum(obj.getString("orderCodeNum"));//订单号
					goldEntry.setStyleCodeNum(obj.getString("styleCodeNum"));//款号
					goldEntry.setKarat(karat);//成色
					goldEntry.setCate(obj.getString("cate"));//种类
					goldEntry.setStyle(obj.getString("style"));//规格
					goldEntry.setCount(obj.getInteger("count"));//数量
					goldEntry.setNoAttritionWeight(obj.getBigDecimal("noAttritionWeight"));//不计耗重
					goldEntry.setGoldWeight(obj.getBigDecimal("goldWeight"));//净金重
					goldEntry.setPureStoneWeight(obj.getBigDecimal("pureStoneWeight"));//石重
					goldEntry.setWithStoneWeight(withStoneWeight);//连石重
					goldEntry.setAttritionRate(obj.getBigDecimal("attritionRate"));//耗率
					goldEntry.setGiveAttrition(obj.getBigDecimal("giveAttrition"));//给耗
					goldEntry.setProcedureUnitPrice(obj.getBigDecimal("procedureUnitPrice"));//工费
					goldEntry.setUnitPrice(obj.getBigDecimal("unitPrice"));//单价金额(￥)
					goldEntry.setCostAmount(obj.getBigDecimal("costAmount"));//价值金额(￥)
					goldEntry.setPayAmount(obj.getBigDecimal("payAmount"));//实付金额(￥)
					goldEntry.setGoldContent(obj.getBigDecimal("goldContent"));//折足率(%)
					goldEntry.setGoldContentWeight(obj.getBigDecimal("goldContentWeight"));//折足重
					goldEntry.setRemark(obj.getString("remark"));//备注
					goldEntryService.save(goldEntry);
				}
			}
			return Result.ok("操作成功！");
		} else {
			return Result.error("操作失败，请勾选要保存的数据！");
		}
	}
	
	/**
	 *  修改
	 *
	 * @param goldEntry
	 * @return
	 */
	@AutoLog(value = " 金出入库-修改")
	@ApiOperation(value=" 金出入库-修改", notes=" 金出入库-修改")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody GoldEntry goldEntry) {
		goldEntryService.updateById(goldEntry);
		return Result.ok("修改成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = " 金出入库-通过id删除")
	@ApiOperation(value=" 金出入库-通过id删除", notes=" 金出入库-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required = true) String id) {
		goldEntryService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = " 金出入库-批量删除")
	@ApiOperation(value=" 金出入库-批量删除", notes=" 金出入库-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required = true) String ids) {
		this.goldEntryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = " 金出入库-通过id查询")
	@ApiOperation(value=" 金出入库-通过id查询", notes=" 金出入库-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required = true) String id) {
		GoldEntry goldEntry = goldEntryService.getById(id);
		if(goldEntry==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(goldEntry);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param goldEntry
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GoldEntry goldEntry) {
        return super.exportXls(request, goldEntry, GoldEntry.class, " 金出入库");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GoldEntry.class);
    }

    

	
	/**
	 *  根据成色获取折足率
	 *
	 * @param goldEntry
	 * @return
	 */
	@AutoLog(value = " 金出入库-获取折足率")
	@ApiOperation(value=" 金出入库-获取折足率", notes=" 金出入库-获取折足率")
	@GetMapping(value = "/getGoldContentByKaratId")
	public Result<?> getGoldContentByKaratId(@RequestParam(name="karat",required = true) String karat) {
		String goldContent = goldEntryMapper.getGoldContentByKaratId(karat);
		return Result.OK(goldContent);
	}
	
	
	/**
	 *  获取发出/接收员工的姓名
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = " 金出入库-获取接收员工的姓名")
	@ApiOperation(value=" 金出入库-获取接收员工的姓名", notes=" 金出入库-获取接收员工的姓名")
	@GetMapping(value = "/getPerson")
	public Result<?> getPerson(@RequestParam(name="username",required = true) String username) {
		SysUser sysUser = sysUserService.getUserByName(username);
		return Result.OK(sysUser.getRealname()+"("+sysUser.getWorkNo()+")");
	}
	
	/**
	 *  获取发出/接收客户的姓名
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = " 金出入库-获取接收客户的姓名")
	@ApiOperation(value=" 金出入库-获取接收客户的姓名", notes=" 金出入库-获取接收客户的姓名")
	@GetMapping(value = "/getCustomer")
	public Result<?> getCustomer(@RequestParam(name="id",required = true) String id) {
		CustomerInfo customerInfo = customerInfoService.getById(id);
		return Result.OK(customerInfo.getCusName());
	}
	
	/**
	 *  获取发出/接收仓库的姓名
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = " 金出入库-获取接收仓库的姓名")
	@ApiOperation(value=" 金出入库-获取接收仓库的姓名", notes=" 金出入库-获取接收仓库的姓名")
	@GetMapping(value = "/getStorage")
	public Result<?> getStorage(@RequestParam(name="id",required = true) String id) {
		String sendStorage = goldEntryService.getStorageName(id);
		return Result.OK(sendStorage);
	}
}
